package com.ficus.road.maintain.ditalTwin.service;

import com.ficus.road.maintain.core.model.GpsHistory;
import com.ficus.road.maintain.core.model.digitalTwin.Asset;
import com.ficus.road.maintain.core.model.digitalTwin.LaneInfo;
import com.ficus.road.maintain.dao.GpsHistoryDao;
import com.ficus.road.maintain.ditalTwin.dao.AssetDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.MatchOperation;
import org.springframework.data.mongodb.core.aggregation.SortOperation;
import org.springframework.data.mongodb.core.query.Criteria;

import org.springframework.stereotype.Service;


import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
@Slf4j
public class DigitalAssetService {

    @Autowired
    AssetDao assetDao;

    @Autowired
    GpsHistoryDao gpsHistoryDao;
    private Map<String,String> trackIdToMapIdMap;


    @PostConstruct
    public void init() {
        List<Asset> all = assetDao.findAll();
        trackIdToMapIdMap = all.stream().collect(Collectors.toMap(Asset::getTrackId, as-> as.getMapId() == null ? "": as.getMapId()));
    }

    public String getMapIdByTrackId(String trackId) {
        return trackIdToMapIdMap.get(trackId);
    }

    /**
     * 查询道路长度宽度
     * @param creationTime
     * @return
     */
    public LaneInfo getLaneInfo(long creationTime) {
        //筛选"timestamp"字段大于等于给定的time值的文档
        MatchOperation matchOperation = Aggregation.match(Criteria.where("timestamp").gte(creationTime));
        //根据"timestamp"字段将文档按升序排序
        SortOperation sortOperation = Aggregation.sort(Sort.Direction.ASC, "timestamp");
        Aggregation aggregation = Aggregation.newAggregation(matchOperation, sortOperation, Aggregation.limit(1));
        List<GpsHistory> aggregate = gpsHistoryDao.aggregate(aggregation);

        if (!aggregate.isEmpty()) {
            //如果找到匹配的数据，返回LaneInfo
            return aggregate.get(0).getLaneInfo();
        } else {
            return null; //如果没有找到匹配的数据，返回null
        }
    }
}
